package com.luisliuyi.plugin.channel;

import com.luisliuyi.plugin.channel.data.Apk;

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ChannelTask extends DefaultTask {
    private ChannelExtensions channelExtensions;

    public ChannelTask() {
        setGroup("渠道包");
        setDescription("生成渠道包");
        channelExtensions = getProject().getExtensions().getByType(ChannelExtensions.class);
    }

    @TaskAction
    void run() {
        File baseApk = new File(channelExtensions.baseApk);
        File channelFile = new File(channelExtensions.channelFile);
        File outDir = new File(channelExtensions.outDir);
        outDir.mkdirs();

        String name = baseApk.getName();
        name = name.substring(0, name.lastIndexOf("."));

        try {
            List<String> channels = readChannelFile(channelFile);
            Apk apk = ApkParser.parser(baseApk);
            for (String channel : channels) {
                File file = new File(outDir, name + "-" + channel +
                        ".apk");
                ApkBuilder.generateChannel(channel, apk, file);
            }

        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<String> readChannelFile(File channelFile) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(new
                FileInputStream(channelFile)));
        List<String> list = new ArrayList<>();
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        return list;
    }
}
